/**
 * 工作单位：IT创新工作室
 * 文件名：MqttService
 * 作者：cheru
 * 日期：2019/11/21 0:53
 */
package com.itgzs.back.service;

import com.itgzs.back.bean.Sensor;
import com.itgzs.back.mapper.SensorMapper;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class SensorService {

    public static final String MQTT_BROKER_HOST = "tcp://192.168.137.41:1883";
    public static final String MQTT_CLIENT_ID = "sensor";

    public static final String USERNAME = "admin";
    public static final String PASSWORD = "password";

    private volatile static MqttClient mqttClient;
    private static MqttConnectOptions options;

    //订阅主题
    public static final String[] MQTT_TOPICS = {
            "itgzs/light_sensor/value",
            "itgzs/cc811/co2/value",
            "itgzs/cc811/voc/value",
            "itgzs/dht11/temp/value",
            "itgzs/dht11/humidity/value",
    };

    @Autowired
    private Sensor sensor;

    @Autowired
    private SensorMapper sensorMapper;

    static {
        try {
            // host为主机名，clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，
            // MemoryPersistence设置clientid的保存形式，默认为以内存保存
            mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
            // 配置参数信息
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
            // 这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置用户名
            options.setUserName(USERNAME);
            // 设置密码
            options.setPassword(PASSWORD.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            // 连接
            mqttClient.connect(options);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Scheduled(fixedRate = 1000)
    public void sensorData() {

        try {
            // 订阅
            for(String MQTT_TOPIC : MQTT_TOPICS){

                mqttClient.subscribe(MQTT_TOPIC, 2);
                // 设置回调
                mqttClient.setCallback(new MqttCallback() {
                    @Override
                    public void connectionLost(Throwable throwable) {
                        System.out.println("connection Lost");
                    }

                    @Override
                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        System.out.println("Topic: " + topic + " Message: " + message.toString());

                        String value = message.toString();

                        switch (topic){
                            case "itgzs/light_sensor/value" : sensor.setLight(value); break;
                            case "itgzs/cc811/co2/value" : sensor.setCo2(value); break;
                            case "itgzs/cc811/voc/value" : sensor.setVoc(value); break;
                            case "itgzs/dht11/temp/value" : sensor.setTemp(value); break;
                            case "itgzs/dht11/humidity/value" : sensor.setHumidity(value);break;
                        }

                        sensorMapper.updateSenser(sensor);

                    }

                    @Override
                    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {}
                });
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}